package BlockingQueue_12;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class 工作线程池_LinkedBlockingQueue {
    public static void main(String[] args) {
        final int WORKER_COUNT = 4;
        final int TASK_COUNT = 20;
        final BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>();

        // 创建工作线程
        for (int i = 0; i < WORKER_COUNT; i++) {
            final int workerId = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        while (true) {
                            Runnable task = taskQueue.take();
                            System.out.println("工作者 " + workerId + " 开始执行任务");
                            task.run();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "工作者-" + i).start();
        }

        // 提交任务
        for (int i = 0; i < TASK_COUNT; i++) {
            final int taskId = i;
            taskQueue.add(new Runnable() {
                public void run() {
                    try {
                        System.out.println("任务 " + taskId + " 正在执行");
                        Thread.sleep((long)(Math.random() * 500)); // 模拟任务执行时间
                        System.out.println("任务 " + taskId + " 完成");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            System.out.println("已提交任务 " + taskId);
        }
    }
}